/**
 * @description service payment
 *
 * @author Xiongmao
 */
'use strict';

const IAP = require('in-app-purchase');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
// const Promise = require('bluebird');

// 验证 webhooks 签名
const verifySignature = function(data, signature) {
    console.log(data, signature);
    const verifier = crypto.createVerify('RSA-SHA256').update(JSON.stringify(data), 'utf8');
    const pubkey = fs.readFileSync(process.env.PING_RSA_PUBLIC_KEY, 'utf8');
    return verifier.verify(pubkey, signature, 'base64');
};

// const pingpp = require('pingpp')(process.env.PINGPP_KEY);

const iap = function(body, transactionId) {
    return new Promise(function(resolve, reject) {
        IAP.config({
            // applePassword: '1234567890abcdef1234567890abcdef',
            verbose: false
        });
        IAP.setup(function(err) {
            if(err) {
                return reject(err);
            }
            // iap is ready
            IAP.validate(IAP.APPLE, body.receipt_data, function(err, res) {
                if(err) {
                    err.code = res.status;
                    return reject(err);
                }
                if(IAP.isValidated(res)) {
                    // yay good!
                    var data = IAP.getPurchaseData(res, { ignoreExpired: true });
                    if(transactionId) {
                        for(let i = 0; i < data.length; i++) {
                            if(data[i].transactionId === transactionId) {
                                return resolve(data[i]);
                            }
                        }
                    }
                    return resolve(data[data.length - 1]);
                }
            });
        });
    });
};

const pingppPay = function * (order, body) {
    const hooks = {
        'charge.succeeded': function * () {
            if(!body.data.object.paid) {
                this.throw(400, '未支付');
            }
            if(!body.data.object.amount === order.get('ammount')) {
                this.throw(400, '支付金额非法');
            }
            yield order.save({
                status: 1
            }, {
                patch: true,
            });
            return true;
        },
    };
    return yield hooks[body.type]();
    // 修改订单的支付状态
};


module.exports = {
    iap: iap,
    verifySignature: verifySignature,
    pingpp: pingppPay
};
